<template>
  <div class="page">
    <v-pageTitle title="用户管理"></v-pageTitle>
    <v-pageHeader>
        <el-button size="small" type="primary" icon="el-icon-circle-plus" v-if="hasPermission('新增')" @click="batchAdd">新增</el-button>
        <el-button size="small" type="danger" icon="el-icon-remove" v-if="hasPermission('删除')" :disabled="this.sels.length===0" @click="del">删除</el-button>
        <el-button size="small" type="info" icon="el-icon-circle-close-outline" v-if="hasPermission('注销')" :disabled="this.sels.length===0" @click="changeStatus">注销</el-button>
        <el-button size="small" type="success" icon="el-icon-download" v-if="hasPermission('导出')" @click="doExport">导出</el-button>
    </v-pageHeader>
    
    <imp-panel>
      <v-pageSearch v-if="hasPermission('查询')">
        <el-row style="width: 100%;">
          <el-form :inline="true">
            <el-col :span="24">
              <!-- <el-form-item label="所属部门">
                <el-autocomplete
                  size="small"
                  popper-class="my-autocomplete"
                  v-model="formSearch.companyName"   
                  :fetch-suggestions="querySearchAsync_companyName"
                  placeholder="请输入查询关键字"
                  suffix-icon="el-icon-search"
                  @select="handleSelect_companyName"
                  @blur="getDefault_companyName"
                >
                  <template slot-scope="props_companyName">
                    <div class="name">{{ props_companyName.item.value }}</div>
                    <span class="label">{{ props_companyName.item.label }}</span>
                  </template>
                </el-autocomplete>
              </el-form-item> -->
              <el-form-item label="所属部门"> 
                <el-select v-model="formSearch.companyId" filterable size="small" placeholder="请选择">
                  <el-option
                    v-for="item in depsList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="姓名">
                <el-input v-model="formSearch.name" size="small" placeholder="请输入"></el-input>
              </el-form-item>
              <el-form-item label="工号">
                <el-input type="number" v-model="formSearch.usercode" size="small" placeholder="请输入"></el-input>
              </el-form-item>
              <el-form-item label="用户状态">
                <el-select v-model="formSearch.enabled" size="small" placeholder="请选择">
                  <el-option
                    v-for="item in status_options"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button size="small" type="primary" icon="el-icon-search" @click="onSearch">查询</el-button>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </v-pageSearch>
      
      <v-pageTable pagination :sizeChange="sizeChange" :pageChange="pageChange" :paginationTotal="paginationTotal" paginationAlign="right">
        <el-table size="small" v-loading="table.loading"  
          :max-height="table.autoHeight"
          :data="table.body" style="width: 100%" @selection-change="selsChange" 
          :header-row-style='headerBg' :header-cell-style="headerBg"
          :default-sort="{prop: 'date', order: 'descending'}">
            <el-table-column fixed type="selection" width="45">
            </el-table-column>
            <el-table-column prop="usercode" label="员工工号" min-width="100" sortable>
            </el-table-column>
            <el-table-column prop="name" label="姓名" min-width="70" sortable>
            </el-table-column>
            <el-table-column prop="username" label="登录名" min-width="100" sortable>
            </el-table-column>
            <el-table-column prop="companyName" label="所属部门" min-width="120" sortable>
            </el-table-column>
            <el-table-column prop="userNameVu" label="角色名称" min-width="120" sortable>
            </el-table-column>
            <el-table-column prop="address" label="详细住址" min-width="200" sortable>
            </el-table-column>
            <el-table-column prop="remark" label="备注" min-width="120" sortable>
            </el-table-column>
            <el-table-column prop="phone" label="联系方式" min-width="120" sortable>
            </el-table-column>
            <el-table-column prop="enabled" label="账户状态" min-width="100" sortable>
              <template slot-scope="scope">
                <el-tag
                  size="small" :type="scope.row.enabled | enabledFilterType">{{getName_enabled(scope.row.enabled)}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="250">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="default"
                  icon="edit"
                  v-if="hasPermission('编辑')"
                  @click="batchEdit(scope.row)">编辑
                </el-button>
                <el-button
                  size="mini"
                  type="danger"
                  v-if="hasPermission('删除')"
                  @click="handleDel(scope.$index, scope.row)">删除
                </el-button>
                <el-button
                  size="mini"
                  type="info"
                  v-if="hasPermission('重置密码')"
                  @click="restPassword(scope.$index, scope.row)">重置密码
                </el-button>
              </template>
            </el-table-column>
        </el-table>
      </v-pageTable>
    </imp-panel>

    <!--编辑界面-->
    <el-dialog :title="editTitle" top="30px" :visible.sync="editFormVisible" @close="dialogClose('dialogForm')" :close-on-click-modal="false">
      <el-form :model="dialogForm" :rules="rules" ref="dialogForm" label-width="100px" size="mini">
        <el-form-item label="员工工号" prop="usercode">
          <el-input type="number" v-model="dialogForm.usercode" :readonly="!isAdd"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="dialogForm.name"></el-input>
        </el-form-item>
        <el-form-item label="登录名" prop="username">
          <el-input v-model="dialogForm.username" :readonly="!isAdd"></el-input>
        </el-form-item>
        <el-form-item label="所属部门" prop="companyId"> 
          <el-select v-model="dialogForm.companyId" filterable size="small" placeholder="请选择">
            <el-option
              v-for="item in depsEditList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色名称" prop="rids">
          <el-select style="width:100%;" v-model="dialogForm.rids" placeholder="请选择">
            <el-option
              v-for="item in role_options"
              :key="item.id"
              :label="item.nameZh"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="dialogForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="dialogForm.address"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="dialogForm.remark"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button  type="primary" @click.native="submitForm('dialogForm')" :loading="editLoading">提交</el-button>
            <el-button @click="resetForm('dialogForm')">重置</el-button>
            <el-button  @click.native="editFormVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import panel from "@/components/common/panel.vue"
import util from '@/util/util'
  export default {
    components: {
      'imp-panel': panel
    },
    data() {
      // 验证手机号码
      var checkTel = (rule, value, callback) => {
        if(value){
          setTimeout(() => {
            if (!(/^1[34578]\d{9}$/.test(value))) {
              callback(new Error('请填写正确的手机号码格式'));
            } else {
              callback();
            }
          }, 100);
        }else{
          callback();
        }
      };
      // 验证邮箱
      var checkEmail = (rule, value, callback) => {
        if(value){
          setTimeout(() => {
            if (!(/^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/g.test(value))) {
              callback(new Error('请填写正确的邮箱格式'));
            } else {
              callback();
            }
          }, 100);
        }else{
          callback();
        }
      };
      
      return {
        editTitle:'', //编辑界面标题
        role_options: [],
        status_options: [],
        depsList:[],  //查询：部门列表
        depsEditList:[],  //编辑、新增：部门列表
        status_userType: [
          {
            value:0,
            label:"超级用户"
          },
          {
            value:1,
            label:"经理主管"
          },
          {
            value:2,
            label:"普通用户"
          },
        ],  //用户类型
        userTypeValue:"普通用户", //选中的用户类型 
        table: {
            loading: true,
            body: [],
            autoHeight: 634,
            page: 1,
            pageSize: 10
        },
        
        formSearch:{
          name:'',  //姓名
          usercode: '', //工号
          enabled: '',  //用户状态
          companyId:"", //部门Id
        },
        // 模糊查询借助字段 存储上次点选的字段
        value_companyName:'',
        value_companyId: '',

        paginationTotal: 0,
        sels:[],

        isAdd: true,
        //编辑界面数据
        dialogForm: {
          //baseRoleNames: '',
          name: '',
          usercode: '',
          username: '',
          address: '',
          phone: '',
          //companyCode: '',
          companyId: '',
          //companyName: '',
          rids: "",
          remark: '',
        },
        // 模糊查询借助字段 存储上次点选的字段
        value_companyNameForm:'',
        value_companyIdForm: '',

        rules: {
          usercode: [
            { required: true, message: '请输入员工工号', trigger: 'blur' }
            // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          name: [
            { required: true, message: '请输入姓名', trigger: 'blur' }
          ],
          username: [
            { required: true, message: '请输入登录名', trigger: 'blur' }
          ],
          companyId: [
            { required: true, message: '请输入所属部门', trigger: 'blur' }
          ],
          rids: [
            { required: true, message: '请选择角色名称', trigger: 'blur' }
          ],
          companyCode: [
            { required: true, message: '请输入公司代码', trigger: 'blur' }
          ],
        },
        editFormVisible: false,//编辑界面是否显示
        editLoading: false,

        nowDate: util.formatDate.format(new Date(), 'yyyy-MM-dd hh:mm:ss')
      }
    },
    filters: {
      enabledFilterType(statue) {
        let index = statue ? 1 : 0;
        let statusMapType = ['','success','warning','danger']
        return statusMapType[index]
      }
    },
    methods: {
      //编辑界面用户类型改变
      userTypeChange(item){
        console.log(item)
        //console.log(this.userTypeValue)
      },
      // 监控分页数据变化
      currentPage(data){
          this.$store.commit("currentPage", data)
      },
      // 表头样式设置
      headerBg: function(row){
        return { "background": "#EEF1F6","color":"#1F2D3D" };
      },
      //字典数据获取
      baseInfo(){
        let this_ = this;

        //用户状态
        let params_status = {
          "status": 1,
          "type": "user_status"
        };
        util.httpJesen('baseDict/get',params_status,function(data){
          data.data.unshift({"name":"全部","value":''});
          this_.status_options = data.data;
          //console.log(this_.status_options)
        });

        // 获取角色
        let roles_params = {
          "nameZh":"",
          "menuName":""
        };
        util.httpJesen('base/basic/allBaseRoles',roles_params,function(data){
          this_.role_options = data.data;
        });

        // 获取部门
        let deps_params = {};
        util.httpJesen('base/baseDept/getAllDeps',deps_params,function(data){
          data.data.forEach(function(e){
            var param = {
              name:e.name,
              id:e.id,
            }
            this_.depsList.push(param);
            this_.depsEditList.push(param);
          })

          this_.depsList.unshift({"name":"全部","id":""});
        });
      },
      getName_enabled(statue){
        if(this.status_options.length){
          return statue ? '正常' : '已销户';
        }
      },
      // 导出
      doExport(){
        let statusValue = 0;
        
        if(this.formSearch.enabled == 'true'){
          statusValue = 1;
        }else{
          if(this.formSearch.enabled==''){
            statusValue = 0;
          }else{
            statusValue = 2;
          }
        }

        let params = {
          "mapSearch":{
            "companyId": this.formSearch.companyId,
            "usercode": this.formSearch.usercode,
            "name": this.formSearch.name,
            "statusValue": statusValue
          },
          "type": 'ExportUser'
        }; 
        let this_ = this;
        
        let paramsStr = JSON.stringify(params);
        window.location.href = "/api/export/do?data="+encodeURI(paramsStr);
      },
      
      onSearch(){
        this.pageChange(1,'page')
        this.currentPage(1)
      },
      getTableData(val,flag) {
        // ajax 查询表格数据
        let this_ = this;
        this_.table.loading = true;
        let url = 'base/baseUser/getBaseUsersByKeywords';
        if(flag==='pageSize'){
          this.table.pageSize = val;
        }else if(flag==='page'){
          this.table.page = val;
        };
        
        // 处理数据
        function changeToData(json){
          json.forEach(function(item){
            let arr1=[];
            let arr2=[];
            if(item.baseRoles.length>0){
              item.baseRoles.forEach(function(data){
                arr1.push(data.nameZh)
                arr2.push(data.id)
              });
            }
            item['baseRoleNames'] = arr1.join('、');
            item['rids'] = arr2;
          });
          return json;
        };

        
        let params = {};

        if(this.formSearch.enabled!==''){
           params = {
            "page": this.table.page,
            "companyId": this.formSearch.companyId,
            "pageSize": this.table.pageSize,
            "usercode": this.formSearch.usercode,
            "name": this.formSearch.name,
            "enabled": this.formSearch.enabled
          };
        }else{
           params = {
            "page": this.table.page,
            "companyId": this.formSearch.companyId,
            "pageSize": this.table.pageSize,
            "usercode": this.formSearch.usercode,
            "name": this.formSearch.name,
            "statusValue": 0
          };
        }

        util.httpJesen(url,params,function(data){
          //this_.table.body = changeToData(data.data.records);
          this_.table.body = data.data.records;
          this_.paginationTotal = data.data.total;
          this_.table.loading = false;
          this_.editFormVisible = false;
        });
      },
      sizeChange(val){
        this.getTableData(val,'pageSize')
      },
      pageChange(val){
        this.getTableData(val,'page')
        this.currentPage(val)
      },
      
      //行选取事件
      selsChange: function (sels) {
				this.sels = sels;
			},
      //显示新增界面
      batchAdd(){
        this.editTitle = "新增"
        this.editFormVisible = true;
        this.isAdd = true;
        setTimeout(()=>{
          this.resetForm('dialogForm')
        },200)
      },
      //显示编辑界面
			batchEdit: function (row) {
        this.editTitle = "编辑"
				this.editFormVisible = true;
        this.isAdd = false;
        this.dialogForm = Object.assign({}, row);
        this.value_companyNameForm = row.companyName;
        this.value_companyIdForm = row.companyId;
			},
      //close 关闭的回调
      dialogClose(formName){
        this.resetForm(formName)
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let this_ = this;
            this_.editLoading = true;
            let params = Object.assign({}, this_.dialogForm);
            delete params['baseRoleNames']

            let url = this_.isAdd ? 'base/baseUser/addUser' : 'base/baseUser/updateBaseUser';
            let paramsLast = this_.isAdd ? params : [params];

            util.httpJesen(url,paramsLast,function(data){
              this_.editFormVisible = false;
              this_.getTableData()
            });

            setTimeout(function(){
              this_.editLoading = false;
            },2000);
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      // 重置
      resetForm(formName) {
        this.$refs[formName].resetFields();
        this.dialogForm = {
          //baseRoleNamesName: '',
          name: '',
          username:'',
          usercode: '',
          address: '',
          phone: '',
          //companyCode: '',
          companyId: '',
          //companyName: '',
          rids: "",
          remark: ''
        };
        this.value_companyIdForm = '';
        this.value_companyNameForm = '';
      },
      //删除
			handleDel: function (index, row) {
        let this_ = this;
				this.$confirm('确认删除该用户吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this_.table.loading = true;
          let url = 'base/baseUser/deleteBaseUser';
          // let params = {'baseUserId':row.id};
          util.httpJesen(url,[row.id],function(data){
            this_.getTableData();
            this_.table.loading = false;
            this_.$message({
              message: '删除成功',
              type: 'success'
						});
          });
				}).catch(() => {
          console.log(222)
				});
			},
      del: function (index, row) {
        let this_ = this;
        let idArr = [];
        
        this_.sels.forEach(function(item){
          idArr.push(item.id)
        })
        this.$confirm('确认删除这些用户吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this_.table.loading = true;
          let url = 'base/baseUser/deleteBaseUser';
          // let params = {'baseUserId':row.id};
          util.httpJesen(url,idArr,function(data){
            this_.getTableData();
            this_.table.loading = false;
            this_.$message({
              message: '删除成功',
              type: 'success'
            });
          });
        }).catch(() => {

        });
			},
      //重置密码
      restPassword(index,row){
        console.log(row)
        let this_ = this;
        let params = {
          'id': row.id,
          'username':row.username
        };
        let url = 'base/baseUser/resetPassWord';
        
        util.httpJesen(url,params,function(data){
          this_.$message({
            message: '重置密码成功',
            type: 'success'
          });
        });
      },
      //注销
      changeStatus(){
        let this_ = this;
        let OK = true;
        let idArr = [];
        for(var i in this_.sels){
          if(this_.sels[i].enabled ==false){
            this_.$notify({
              title: '警告',
              message: '当前用户中存在已注销用户，不能再次注销！',
              type: 'warning'
            });
            OK = false;
            return;
          }
          idArr.push(this_.sels[i].id)
        }
        
        if(OK){
          this.$confirm('确认注销这些用户吗?', '提示', {
            type: 'warning'
          }).then(() => {
            this_.table.loading = true;
            let url = 'base/baseUser/updateBaseUser';
            this_.sels.forEach(function(item){
              item.enabled = false;
            });
            // let params = {'baseUserId':row.id};
            util.httpJesen(url,this_.sels,function(data){
              this_.getTableData();
              this_.table.loading = false;
              this_.$message({
                message: '注销成功',
                type: 'success'
              });
            });
          }).catch(() => {

          });
        }
      }
    },
    mounted() {
      // 获取table数据
      this.onSearch();
      this.baseInfo();

        //监控浏览器高度 设置table最大高度
      let this_ = this;
      let clientHeight = document.body.clientHeight; 
      this_.table.autoHeight = clientHeight-340;
      window.addEventListener('resize', function(){
        let clientHeight = document.body.clientHeight; 
        this_.table.autoHeight = clientHeight-340;
      });

      this.timer = setInterval(function(){
          this_.nowDate = util.formatDate.format(new Date(), 'yyyy-MM-dd hh:mm:ss');
      },1000);
    },
    beforeDestory(){
        if(this.timer){
            clearInterval(this.timer)
        }
    }
  }
</script>
<style lang="scss" scoped>
.my-autocomplete {
  li {
    line-height: 12px;
    padding: 2px;

    .name {
      text-overflow: ellipsis;
      overflow: hidden;
      height:24px;
    }
    .label {
      font-size: 12px;
      color: #1381B8;
    }

    .highlighted .label {
      color: #ddd;
    }
  }
}
</style>